<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link type="text/css" href="jquery-ui/css/smoothness/jquery-ui-1.8.9.custom.css" rel="stylesheet" />
<script type="text/javascript" src="jquery-ui/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="jquery-ui/js/jquery-ui-1.8.9.custom.min.js"></script>
<script type="text/javascript" src="i18n.js" charset="utf-8"></script>
<script type="text/javascript" src="filterupdate.js" charset="utf-8"></script>
<title>Adblock Plus Options</title>
<style type="text/css" media="screen">
body {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 13px;
    padding: 20px;
}

td {
    font-size: 13px;
    vertical-align: top;
    text-align: left;
}

p {
    margin-top: 0.5em;
}

.rawFilters {
    display: none;
}

.okMsg {
    display: none;
    color: #ffffff;
    background: #30e030;
    font-weight: bold;
    padding: 3px;
}

.errMsg {
    display: none;
    color: #ffffff;
    background: #e03030;
    font-weight:bold;
    padding:3px;
}

/* Filter list entry status message */
.flMsg {
    display: none;
    color: #b0b0b0;
}

</style>
<script type="text/javascript" charset="utf-8">

function loadCheckbox(id) {
    document.getElementById(id).checked = typeof localStorage[id] == "undefined" ? false : localStorage[id] == "true";
}

function saveCheckbox(id) {
    localStorage[id] = document.getElementById(id).checked;
}

function showUserFilters() {
    var userFilters = localStorage["userFilters"];
    if(typeof userFilters == "undefined")
        userFilters = JSON.stringify(["qux.us###annoying_AdDiv", "qux.us##.ad_class"]);
    userFilters = JSON.parse(userFilters);
    // Populate list box with filter strings
    $("#userFiltersBox").children().remove();
    for(var i = 0; i < userFilters.length; i++)
        appendToListBox("userFiltersBox", userFilters[i]);
}

// Loads options from localStorage and sets UI elements accordingly
function loadOptions() {
    // Show icon in address bar?
    loadCheckbox("shouldShowIcon");
    loadCheckbox("shouldShowBlockElementMenu");
    loadCheckbox("disableInlineTextAds");
    loadCheckbox("specialCaseYouTube");
    
    // Load user filter URLs
    loadUserFilterURLs();
    for(key in filterFiles) {
        if(!key.match(/^user_/))
            addFilterListEntry(key);
        else
            addUserURLEntry(key, filterFiles[key]);
    }

    // Filter lists enabled state
    var filterFilesEnabled = typeof localStorage["filterFilesEnabled"] == "string" ? JSON.parse(localStorage["filterFilesEnabled"]) : {"easylist": true, "extras": true };
    for(var key in filterFilesEnabled) {
        document.getElementById(key).checked = filterFilesEnabled[key];
    }
        
    // User-entered filters
    showUserFilters();
        
    // Excluded domains - sort these alphabetically
    var excludedDomains = localStorage["excludedDomains"];
    if(typeof excludedDomains == "string") {
        excludedDomains = JSON.parse(excludedDomains);
        var buf = [];
        for(var domain in excludedDomains)
            buf.push(domain);
        buf.sort();
        for(var i = 0; i < buf.length; i++)
            appendToListBox("excludedDomainsBox", buf[i]);
    }
    
    saveOptions(); // Save any defaults that were created
}

// Reads options from UI elements and saves them in localStorage
function saveOptions() {
    saveCheckbox("shouldShowIcon");
    saveCheckbox("shouldShowBlockElementMenu");
    saveCheckbox("disableInlineTextAds");
    saveCheckbox("specialCaseYouTube");
    
    // Filter lists
    var filterFilesEnabled = {};
    var userFilterURLs = {};
    for(var key in filterFiles) {
        filterFilesEnabled[key] = document.getElementById(key).checked;
        if(key.match(/^user_/)) { // User-added filter?
            userFilterURLs[key] = document.getElementById(key + "_url").textContent;
        }
    }
    localStorage["filterFilesEnabled"] = JSON.stringify(filterFilesEnabled);
    localStorage["userFilterURLs"] = JSON.stringify(userFilterURLs);
    
    // Grab contents of userFiltersBox as an array and JSONify it
    var userFiltersBox = document.getElementById("userFiltersBox");
    var userFilters = [];
    for (var i = 0; i < userFiltersBox.length; i++)
        userFilters.push(userFiltersBox.options[i].value);
    localStorage["userFilters"] = JSON.stringify(userFilters);
    
    // Reload filters and force display of status message
    chrome.extension.sendRequest({reqtype: "reload-filters"}, function() { checkAllFilterLists(); });
    
    // Excluded domains
    var excludedDomainsBox = document.getElementById("excludedDomainsBox");
    var excludedDomains = {};
    for (var i = 0; i < excludedDomainsBox.length; i++)
        excludedDomains[excludedDomainsBox.options[i].value] = true;
    localStorage["excludedDomains"] = JSON.stringify(excludedDomains);    
}

// Add a filter string to the list box.
function appendToListBox(boxId, text) {
    var elt = document.createElement("option");
    elt.text = text;
    elt.value = text;
    document.getElementById(boxId).add(elt, null);
}

function addWhitelistDomain() {
    var domain = document.getElementById("newWhitelistDomain").value.split(' ').join('');
    appendToListBox("excludedDomainsBox", domain);
    saveOptions();
}

// Adds filter text that user typed to the selection box
function addTypedFilter() {
    var filterText = document.getElementById("newFilter").value.replace(/^\s*(.+?)\s*$/g, "$1");
    // ABP filters accept also CSS selectors, spaces are allowed inside filter
    if(filterText == "") return;
    appendToListBox("userFiltersBox", filterText);
    saveOptions();
}

// Removes currently selected whitelisted domains
function removeSelectedExcludedDomain() {
    var excludedDomainsBox = document.getElementById("excludedDomainsBox");
    for (var i = excludedDomainsBox.length-1; i >= 0; i--) {
        if (excludedDomainsBox.options[i].selected)
            excludedDomainsBox.remove(i);
    }
    saveOptions();
}

// Removes all currently selected filters
function removeSelectedFilters() {
    var userFiltersBox = document.getElementById("userFiltersBox");
    for (var i = userFiltersBox.length-1; i >= 0; i--) {
        if (userFiltersBox.options[i].selected)
            userFiltersBox.remove(i);
    }
    saveOptions();
}

// Shows raw filters box and fills it with the current user filters
function toggleFiltersInRawFormat() {
    $(".rawFilters").toggle();
    if($(".rawFilters").is(":visible")) {
        var userFilters = localStorage["userFilters"];
        if(typeof userFilters != "undefined") {
            userFilters = JSON.parse(userFilters);
            document.getElementById("rawFiltersText").value = userFilters.join("\n");
        }
    }
}

// Imports filters in the raw text box
function importRawFiltersText() {
    $(".rawFilters").hide();
    $("#userFiltersBox").children().remove();
    var filters = document.getElementById("rawFiltersText").value.split("\n");
    for(var i = 0; i < filters.length; i++) {
        var text = filters[i].replace(/\s+$/, "").replace(/^\s+/, "");
        if(text.length > 0) {
            // Filter out "comment" characters
            switch(text[0]) {
                case '(': 
                case '[':
                case '!':
                    break;
                default:
                    appendToListBox("userFiltersBox", text);
            }
        }
    }
    saveOptions();
}

// Called when user explicitly requests filter list updates
function updateFilterLists() {
    for(key in filterFiles) {
        // Hide status message
        $("#" + key + "_msg").css("display", "none");
        updateFilterList(key);
    }
    // Now that we've updatd the filter lists, make sure they are loaded
    chrome.extension.sendRequest({reqtype: "reload-filters"});
}

// Updates a single filter list and informs the user what happened
function updateFilterList(key) {
    // Checkbox not checked? Not a URL?
    if(document.getElementById(key).checked == false || !filterFiles[key].match(/^http/i))
        return;
    
    // Hide status message
    $("#" + key + "_msg").css("display", "none");

    new FilterListFetcher(key, function(fetcher) {
        if(fetcher.error) {
            $("#" + fetcher.name + "_msg").text(fetcher.error).css("color", "#a03030").css("display", "inline");
            document.getElementById(key).checked = false;
        } else {
            // Force display of "updated now" message
            checkFilterList(key);
        }
    });
}

// Checks into our possible cached copy of this filter list and updates the UI accordingly
function checkFilterList(key) {
    // Hide status message
    $("#" + key + "_msg").css("display", "none");
    
    var url = filterFiles[key];
    if(url in localStorage) {
        var list = JSON.parse(localStorage[url]);
        if(!list.error) {
            // We didn't used to store lastDownloaded, so we check for its existence and fall back on lastUpdated if necessary
            // lastDownloaded: Last time the list was downloaded
            // lastUpdated: Last time the list reports that it was updated, or else the last time it was downloaded
            var lastDownloaded = list.lastDownloaded ? list.lastDownloaded : list.lastUpdated;
            // Only display status message if checked
            if(document.getElementById(key).checked) {
                var timeDate = i18n_timeDateStrings(lastDownloaded);
                var messageID = (timeDate[1] ? "last_updated_at" : "last_updated_at_today");
                $("#" + key + "_msg").css("color", "#b0b0b0").text(chrome.i18n.getMessage(messageID, timeDate)).css("display", "inline");
            }
        }
        else {
            // Display error only if checked
            if(document.getElementById(key).checked) {
                $("#" + key + "_msg").text(list.error).css("color", "#a03030").css("display", "inline");
            }
        }
    } else {
        // If we don't have this filter list but it's enabled, fetch it
        if(document.getElementById(key).checked == true)
            updateFilterList(key);
    }
}

// Check to see if all filter lists are up to date
function checkAllFilterLists() {
    for(key in filterFiles) {
        checkFilterList(key);
    }
}

// Deletes an entry for a filter list URL from the UI
function deleteUserURLEntry(key) {
    if(key in filterFiles)
        delete filterFiles[key];
    var foo = document.getElementById(key + "_div");
    document.getElementById("userFilterLists").removeChild(foo);
    saveOptions();
}

// Adds an entry for a filter list URL to the UI
function addUserURLEntry(key, url) {
    var checkbox = document.createElement('input');
    checkbox.type = "checkbox";
    checkbox.id = key;
    checkbox.checked = true;
    checkbox.addEventListener("click", function() { saveOptions(); });
    var label = document.createElement('span');
    label.id = key + "_url";
    label.textContent = url + " ";
    var del = document.createElement('span');
    del.appendChild(document.createElement("a"));
    del.firstChild.href = "#";
    del.firstChild.addEventListener("click", function() { deleteUserURLEntry(key);});
    del.firstChild.textContent = "[" + chrome.i18n.getMessage("delete") + "]";
    // Status message
    var msg = document.createElement("span");
    msg.id = key + "_msg";
    msg.class = "flMsg";
    var div = document.createElement('div');
    div.id = key + "_div";
    div.appendChild(checkbox);
    div.appendChild(label);
    div.appendChild(del);
    div.appendChild(msg);
    document.getElementById("userFilterLists").appendChild(div);
}

// Adds an entry for a filter list to the UI.
// TODO: Merge this with addUserURLEntry() as this is too much duplicated code
function addFilterListEntry(key) {
    var checkbox = document.createElement('input');
    checkbox.type = "checkbox";
    checkbox.id = key;
    checkbox.addEventListener("click", function() { saveOptions(); });
    var label = document.createElement('span');
    if(filterListAuthors[key])
        label.innerHTML = chrome.i18n.getMessage("filter_list_desc", [filterListTitles[key], filterListAuthors[key]]);
    else 
        label.innerHTML = filterListTitles[key];
    label.innerHTML += " "; // Space to separate status message from description
    // Status message
    var msg = document.createElement("span");
    msg.id = key + "_msg";
    msg.class = "flMsg";
    var div = document.createElement('div');
    div.id = key + "_div";
    div.appendChild(checkbox);
    div.appendChild(label);
    div.appendChild(msg);
    document.getElementById("filterLists").appendChild(div);
}

// Adds and saves the user-entered filter list URL
function addUserURLFromBox() {
    var key = "user_" + (new Date()).getTime();
    var url = document.getElementById("newURL").value;
    
    // Extract URL from ABP subscription link
    var matches;
    if(matches = url.match(/^abp:\/*?subscribe.*[\?&]location=(.+?)(&|$)/i))
        url = decodeURIComponent(matches[1]);

    if(!url.match(/^http/i) && !url.match(/^file/))
        return;
    addUserURLEntry(key, url);
    document.getElementById("newURL").value = "";
    filterFiles[key] = url;
    // Trigger download
    updateFilterList(key);
    saveOptions();
}

// Set page title to i18n version of "Adblock Plus Options"
document.title = chrome.i18n.getMessage("options");

// Display jQuery UI elements
$(function() { 
    $('#tabs').tabs(); 
    $('button').button(); 
    $('.refreshButton').button('option', 'icons', {primary: 'ui-icon-refresh'});
    $('.addButton').button('option', 'icons', {primary: 'ui-icon-plus'});
    $('.removeButton').button('option', 'icons', {primary: 'ui-icon-minus'});
});


chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if(request.reqtype == "refresh-user-filters-box") {
        // Invoked when user adds clickHide filters
        showUserFilters();
        sendResponse({});
    }
});

</script>
</head>
<body onload="loadI18nStrings(); loadOptions(); checkAllFilterLists()">
<table><tr><td style="padding-right: 8px"><img src="icons/abp-32.png"></td><td><h1><span class="i18n_options"></span></h1></td></tr></table>

<div id="tabs"><ul>
<li><a href="#tab-filterlists"><span class="i18n_filter_lists"></span></a></li>
<li><a href="#tab-userfilters"><span class="i18n_add_your_own_filters"></span></a></li>
<li><a href="#tab-whitelisted"><span class="i18n_whitelisted_domains"></span></a></li>
<li><a href="#tab-general"><span class="i18n_general"></span></a></li>
</ul>

<div id="tab-filterlists">
<p><span class="i18n_enable_only_the"></span></p>
<p><span class="i18n_out_of_date_lists"></span> <button class="refreshButton" onclick="updateFilterLists()"><span class="i18n_update_now"></span></button><br/>
<!-- Placeholder for list of suggested filter lists -->
<div id="filterLists"></div>
<br/>
<!-- Placeholder for user's filter list URLs -->
<div id="userFilterLists" style="margin-bottom: 8px"></div>

<div id="addURLField">  
<span class="i18n_add_a_filter_list">"http://adblockplus.org/en/subscriptions"</span><br/>
<input type="text" value="" id="newURL" style="width:500px">
<button class="addButton" onClick="addUserURLFromBox()"><span class="i18n_add_url_button"></span></button><br/>
</div>
</div>

<div id="tab-whitelisted">
<p class="i18n_disabled_for_these_domains"></p>

<table>
<tr><td style="max-width:100%">
<input type="text" value="" id="newWhitelistDomain" style="width:100%"></td>
<td><button class="addButton" onClick="addWhitelistDomain()"><span class="i18n_add_domain_button"></span></button></td></tr>

<tr><td>
<select id="excludedDomainsBox" size="10" multiple style="width:500px; background: white;">
</select></td><td>
<button class="removeButton" onClick="removeSelectedExcludedDomain()"><span class="i18n_remove_button"></span></button>
</td></tr></table>
</div>
<div id="tab-userfilters">
<p class="i18n_filter_must_follow_syntax">"http://adblockplus.org/en/filters"</p>

<table>
<tr><td>
<input type="text" value="" id="newFilter" style="width:500px"></td>
<td><button class="addButton" onClick="addTypedFilter()"><span class="i18n_add_filter_button"></span></button></td></tr>
<tr><td>
<select id="userFiltersBox" size="20" multiple style="width: 500px; background: white;">
</select>
</td><td>
<button class="removeButton" onClick="removeSelectedFilters()">
<span class="i18n_remove_button"></span></button></td></tr>

<tr><td>
<div style="font-size: 90%; text-align: right"><a onClick="toggleFiltersInRawFormat()" href="#"><span class="i18n_edit_filters_raw"></span></a></div>
</td></tr>
<tr><td>
<div class="rawFilters" style="width: 500px">
<textarea id="rawFiltersText" style="width: 100%; height: 300px"></textarea>   
</div></td>
<td><div class="rawFilters"><button onClick="importRawFiltersText()"><span class="i18n_apply_changes"></span></button></div></td>
</tr></table>

</div>

<div id="tab-general">
<input type="checkbox" id="shouldShowIcon" onClick="saveOptions()" /><span class="i18n_show_icon"></span><br/>
<input type="checkbox" id="shouldShowBlockElementMenu" onClick="saveOptions()" /><span class="i18n_show_block_element_menu"></span><br/>
<input type="checkbox" id="disableInlineTextAds" onClick="saveOptions()" /><span class="i18n_disable_inline"></span><br/>
<input type="checkbox" id="specialCaseYouTube" onClick="saveOptions()" /><span class="i18n_block_youtube"></span><br/>

<br/>
<span class="i18n_found_a_bug">"https://adblockplus.org/forum/viewforum.php?f=10"</span>

</div>
</div>
</body>
</html>
